package com.smm.web.mtower.bo;

import com.smm.web.mtower.domain.Camera;
import com.smm.web.mtower.domain.SnapOrder;
import com.smm.web.mtower.util.ImageUtil;
import com.smm.web.mtower.util.MapUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by zhenghao on 2016/6/15.
 * 服务器指令处理
 */

@Service
public class OrderBO {

    @Value("${image.save.path}")
    private String imageSavePath;    //抓拍图片保存路径


    @Resource
    private CameraBO cameraBO;


    public String snap(SnapOrder sorder) throws Exception {

        Camera camera = sorder.getCamera();

        if(camera==null) throw new Exception("camera is null");

        //检查摄像头是否在本机存在
        boolean isExists = checkCamerExists(camera);

        if(!isExists) throw new Exception("camer not in local. ip:"+camera.getIp());

        String imageName = new Date().getTime() +".jpg";

        String imageFallPath = imageSavePath + imageName;

        cameraBO.sanp(camera,imageFallPath);

        //压缩图片
        ImageUtil.reduce(imageSavePath, imageName);

        return imageFallPath;
    }

    /**
     * 检查摄像头是否在本机配置中存在。
     * @param camera
     * @return
     */
    private boolean checkCamerExists(Camera camera) {

        for(String key : MapUtil.TagAndCameraMap.keySet()){

            Camera mapCamera = MapUtil.TagAndCameraMap.get(key);

            if(mapCamera.equals(camera)){

                return true;
            }
        }

        return false;
    }
}
